package com.example.qbbcrssreader;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import java.util.Locale;

import android.app.Activity;
import android.content.Context;
import android.text.Html;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.TextView;

import com.example.qbbcrssreader.R;
import com.example.qbbcrssreader.BBCXmlParser.Entry;

public class LazyAdapter extends BaseAdapter {

	private Activity activity;
	private List<Entry> data = null;
	private static LayoutInflater inflater = null;
	public ImageLoader imageLoader;

	public LazyAdapter(Activity a) {
		activity = a;
		inflater = (LayoutInflater) activity
				.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
		imageLoader = new ImageLoader(activity.getApplicationContext());
	}

	public int getCount() {
		if (data == null) {
			return 0;
		}
		else {
			return data.size();
		}
	}

	public Object getItem(int position) {
		return position;
	}

	public long getItemId(int position) {
		return position;
	}
	
	public void loadData(List<Entry> entries) {
		data = entries;
	}

	public View getView(int position, View convertView, ViewGroup parent) {
		View vi = convertView;
		// Inflate the item View, if not already inflated
		if (convertView == null)
			vi = inflater.inflate(R.layout.item, null);

		// Simply return now, if there is no data
		if (data == null) {
			return vi;
		}
		
		// Get the 'description' and 'title' TextView's
		TextView text = (TextView) vi.findViewById(R.id.text);
		TextView text_title = (TextView) vi.findViewById(R.id.text_title);

		// Set the 'title' and format the date, like the BBC website
		Date date = data.get(position).pubDate;
		SimpleDateFormat format = new SimpleDateFormat ("d MMMM yyyy 'at' HH:mm", Locale.ENGLISH);
		text_title.setText(Html.fromHtml("<b>" + data.get(position).title + "</b><br /><small>"
		                                  + format.format(date) + "</small>"));
		// Set the 'description'
		text.setText(Html.fromHtml(data.get(position).description));
		// Get the url for the thumbnail image
		String url = data.get(position).mediaThumbnail;
		// Get the ImageView and check if the url is null
		ImageView image = (ImageView) vi.findViewById(R.id.image);
		if (url != null) {
			// Get the image via a multi-threaded cache 
			imageLoader.DisplayImage(data.get(position).mediaThumbnail, image);
		}
		else {
			// Otherwise, draw the stub image, a '?'
			image.setImageResource(R.drawable.stub);
		}
		return vi;
	}
}
